package org.aplikator.client.widgets;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.aplikator.client.Aplikator.AplikatorResources;
import org.aplikator.client.data.ListItem;
import org.aplikator.client.descriptor.PropertyDTO;

import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.RadioButton;

public class RadioButtonWidget<T extends Serializable> extends DataFieldBase<T> implements DataField<T> {
    private List<RadioButton> buttons;

    public RadioButtonWidget(String caption, PropertyDTO<T> property, boolean vertical) {
        super(caption, property, true, vertical);
        buttons = new ArrayList<RadioButton>(property.getListValues().size());
        for (ListItem<T> item : property.getListValues()) {
            RadioButton button = new RadioButton(label.getText(), item.getName());
            button.addStyleName(PaneWidgetResources.INSTANCE.css().formData());
            buttons.add(button);
            add(button);
        }
    }

    public void setValue(T value) {
        for (int i = 0; i < getProperty().getListValues().size(); i++) {
            if (getProperty().getListValues().get(i).getValue().equals(value)) {
                buttons.get(i).setValue(true, false);
                return;
            }
        }

    }

    public T getValue() {
        int index = -1;
        for (int i = 0; i < buttons.size(); i++) {
            if (buttons.get(i).getValue()) {
                index = i;
                break;
            }
        }
        if (index == -1) {
            return null;
        }
        return getProperty().getListValues().get(index).getValue();
    }

    public HandlerRegistration addValueChangeHandler(ValueChangeHandler<T> handler) {
        // return box.addChangeHandler(handler);
        return null;
    }

    public void setEnabled(boolean enabled) {
        // box.setEnabled(enabled); //TODO iterate over buttons
    }

    public void setDirty(boolean dirty) {
        super.setDirty(dirty);
        if (dirty) {
            panel.addStyleName(AplikatorResources.INSTANCE.css().dirty());
        } else {
            panel.removeStyleName(AplikatorResources.INSTANCE.css().dirty());
        }
    }

}
